<template>
  <div v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <div class="text-center enter-x min-w-64 min-h-64">
      <!-- <QrCode
        v-model:value="qrCodeValue"
        :logo="Avatar"
        class="flex justify-center enter-x xl:justify-start"
        :width="280"
        v-show="isScan === false"
      /> -->
      <Image
        v-bind="$attrs"
        v-model:src="qrCodeImg"
        class="flex justify-evenly enter-x"
        :width="280"
        :preview="false"
        :fallback="qrcodeEmpty"
      />
      <Divider class="enter-x">{{
        isScan === false ? t('sys.login.scanSign') : t('sys.login.scanSignComplete')
      }}</Divider>
      <Button size="large" block class="mt-4 enter-x" @click="handleBack">
        {{ t('sys.login.backSignIn') }}
      </Button>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, unref, watch } from 'vue';

  import LoginFormTitle from './LoginFormTitle.vue';
  import { Button, Divider, Image } from 'ant-design-vue';
  import { useIntervalFn } from '@vueuse/core';

  import { urlToBase64 } from '@/utils/file/base64Conver';

  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useLoginState, LoginStateEnum } from './useLogin';

  import qrcodeEmpty from '@/assets/images/qrcode_empty.png';
  import qrcodeScan from '@/assets/images/qrcode_scan.png';

  import { router } from '@/router';
  import { PageEnum } from '@/enums/pageEnum';

  import { useIdentityStore } from '@/store/modules/identity';
  import { usePreferenceStoreWithOut } from '@/store/modules/preference';
  import { getQrCodeToken } from '@/api/identity';
  import { RequestClientTypeEnum } from '@/api/identity/model';
  import { QRCodeDto } from '#/request';
  import { JsonWebToken } from '#/identity';

  const { t } = useI18n();
  const { handleBackLogin, getLoginState } = useLoginState();
  const { notification, createMessage } = useMessage();
  const identityStore = useIdentityStore();
  const preferenceStore = usePreferenceStoreWithOut();

  const qrCodeId = ref('');
  const qrCodeValue = ref('');
  const qrCodeImg = ref('');
  const isScan = ref(false);

  const intervalFnReturn = useIntervalFn(handleQrCodeToken, 3 * 1000);

  const getShow = computed(() => {
    const isShow = unref(getLoginState) === LoginStateEnum.QR_CODE;
    if (!isShow) {
      intervalFnReturn.pause;
    }
    return isShow;
  });

  watch(
    () => {},
    () => {
      if (intervalFnReturn.isActive.value === false) {
        intervalFnReturn.resume;
      }
      handleQrCodeToken();
    },
    { immediate: true },
  );

  /** 处理二维码令牌数据 */
  async function handleQrCodeToken() {
    if (getShow.value === true) {
      let logoImage = preferenceStore.getLogo;
      if (logoImage.startsWith('/')) {
        logoImage = await urlToBase64(logoImage);
      }
      const result = await getQrCodeToken({
        Id: qrCodeId.value,
        ClientType: RequestClientTypeEnum.Browser,
        ClientId: null,
        ProviderKey: null,
        OrganizationId: null,
        LogoImage: logoImage,
      });
      if (result.Succeeded) {
        const token = result.Data as JsonWebToken;
        if (token.AccessToken) {
          await identityStore.loginEnd(token);
          const userInfo = await identityStore.afterLoginAction();
          if (userInfo) {
            intervalFnReturn.pause;
            const sessionTimeout = computed(() => identityStore.getSessionTimeout);
            sessionTimeout.value && identityStore.setSessionTimeout(false);
            !sessionTimeout.value && (await router.replace(PageEnum.BASE_HOME));
            await router.replace(PageEnum.BASE_HOME);
            notification.success({
              message: t('sys.login.loginSuccessTitle'),
              description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.NickName}`,
              duration: 3,
            });
          }
        } else {
          const qrCodeDto = result.Data as QRCodeDto;
          // createMessage.success(qrCodeDto.Content.Id);
          if (
            qrCodeId.value !== undefined &&
            qrCodeId.value !== null &&
            qrCodeId.value !== '' &&
            qrCodeDto.Content.Id !== undefined &&
            qrCodeDto.Content.Id !== null &&
            qrCodeDto.Content.Id !== '' &&
            qrCodeId.value !== qrCodeDto.Content.Id
          ) {
            createMessage.info(t('sys.login.scanSignRefreshed'));
          }
          qrCodeId.value = qrCodeDto.Content.Id;
          isScan.value = qrCodeDto.IsScan;
          qrCodeValue.value = JSON.stringify(qrCodeDto.Content);
          qrCodeImg.value = isScan.value === false ? qrCodeDto.Image : qrcodeScan;
        }
      }
    }
  }

  /** 处理返回 */
  async function handleBack() {
    clearFormData();
    handleBackLogin();
  }

  /** 清除表单数据 */
  function clearFormData() {
    qrCodeId.value = '';
    qrCodeValue.value = '';
    qrCodeImg.value = '';
    isScan.value = false;
  }
</script>
